package com.bright.ghj.user.controller;

import com.bright.ghj.common.util.AssertUtil;
import com.bright.ghj.user.properties.CasProperties;
import com.bright.ghj.common.pojo.bo.RestResult;
import com.bright.ghj.user.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * @Author txf
 * @Date 2022/6/24 15:46
 * @Description
 */
@RestController
public class CasController {

    private CasProperties casProperties;

    @Autowired
    public CasController(CasProperties casProperties) {
        this.casProperties = casProperties;
    }

    @GetMapping("/send")
    public RestResult send(HttpServletRequest request) throws MalformedURLException {
//        String url = casProperties.getCasServerLoginUrl() + "?service="
//                + casProperties.getAppServerUrl() + casProperties.getAppLoginUrl();
        // 20251118 兼容多个域名
        // 获取登录网址
        String domain = SecurityUtil.getDomainOfRequestUrl(request);

        String loginUrl = SecurityUtil.getMatchedDomainUrl(casProperties.getCasServerLoginUrl(), domain);
        String appUrl = SecurityUtil.getMatchedDomainUrl(casProperties.getAppServerUrl(), domain);
        AssertUtil.notNull(loginUrl, "未匹配到cas网址，" + domain);
        AssertUtil.notNull(appUrl, "未匹配到登录接口网址，" + domain);
        String url = loginUrl + "?service=" + appUrl + casProperties.getAppLoginUrl();
        return RestResult.fail(401, "用户未登录", url);
    }

    @GetMapping("/login")
    public RestResult login() {
        return RestResult.success();
    }

    @GetMapping("/logout")
    public RestResult logout(HttpServletRequest request) throws MalformedURLException {
//        String url = casProperties.getCasServerLogoutUrl() + "?service="
//                + casProperties.getAppHomeUrl();
        String domain = SecurityUtil.getDomainOfRequestUrl(request);
        String homeUrl = SecurityUtil.getMatchedDomainUrl(casProperties.getAppHomeUrl(), domain);
        AssertUtil.notNull(homeUrl, "未匹配到首页网址，" + domain);
        String url = casProperties.getCasServerLogoutUrl() + "?service=" + homeUrl;
        return RestResult.fail(401, "用户未登录", url);
    }
}
